package com.atguigu.gulimall.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.common.utils.HttpUtils;
import com.atguigu.common.utils.JwtUtils;
import com.atguigu.common.utils.MD5Util;
import com.atguigu.common.utils.R;
import com.atguigu.common.vo.MemberInfoVo;
import com.atguigu.common.vo.MemberVo;
import com.atguigu.gulimall.config.WBProperties;
import com.atguigu.gulimall.config.WBUrl;
import com.atguigu.gulimall.fegin.MemberRegister;
import com.atguigu.gulimall.vo.UserRegisterVo;
import com.google.gson.Gson;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;

@Controller
public class LoginController {
    @Autowired
    StringRedisTemplate redisTemplate;
    @Autowired
    MemberRegister member;

    @Autowired
    WBProperties wbProperties;


    @GetMapping("/login.html")
    public  String login(){
        return  "login";
    }
    @GetMapping("/register.html")
    public  String register(){
        return  "register";
    }

    //注册成功重定向

    /**
     * 分布式下的session
     * @param vo
     * @param result
     * @param attributes
     * @return
     */
    @PostMapping("/redirect")
    public String reg(@Valid UserRegisterVo vo, BindingResult result, RedirectAttributes attributes){
        //校验出错
        if (result.hasErrors()){
            Map<String, String> collect = result.getFieldErrors().stream().collect(Collectors.toMap(FieldError::getField, FieldError::getDefaultMessage,(v1,v2)->v1));
            attributes.addFlashAttribute("errors",collect);
            return "redirect:http://auth.gulimall.com/register.html";
        }
        //校验验证码
        String code = redisTemplate.opsForValue().get(vo.getPhone());
        if (vo.getCode().equals(code)){
            //删除验证码
            redisTemplate.delete(vo.getPhone());
            //验证码正确
            R r = member.register(vo);
            if (r.getCode()==0){
                //校验成功
                return "redirect:http://auth.gulimall.com/login.html";
            }else {
                Map<String, String> errors=new HashMap<>();
                errors.put("username","注册失败");
                attributes.addFlashAttribute("errors",errors);
                return  "redirect:http://auth.gulimall.com/register.html";
            }

        }else {
            Map<String, String> errors=new HashMap<>();
            errors.put("code","验证码错误");
            attributes.addFlashAttribute("errors",errors);
            return  "redirect:http://auth.gulimall.com/register.html";
        }


    }
    @GetMapping("/userlogin")
    public String login(@RequestParam String phone, @RequestParam String password,RedirectAttributes attributes){
        R login = member.login(phone, password);
        if (login.getCode()==0){
            return  "redirect:http://gulimall.com";
        }else {
            Map<String, String> errors=new HashMap<>();
            errors.put("code","电话号或密码错误");
            attributes.addFlashAttribute("errors",errors);
            return  "redirect:http://auth.gulimall.com/login.html";
        }

    }

    @GetMapping("/weibo")
    public String weibo(){
       return "redirect:https://api.weibo.com/oauth2/authorize?client_id=1886146627&response_type=code&redirect_uri=http://auth.gulimall.com/oauth2/weibo";

    }


    //oauth2.0
    @GetMapping("/oauth2/weibo")
    public  String  oauth2Weibo(@RequestParam String code, HttpServletResponse response1) throws Exception {
        Map<String,String> map=new HashMap();
        map.put("client_id",wbProperties.getAppKey());
        map.put("client_secret",wbProperties.getAppSecret());
        map.put("redirect_uri",wbProperties.getRedirectUri());
        map.put("grant_type","authorization_code");
        map.put("code",code);
        HttpResponse post = HttpUtils.doPost("https://api.weibo.com","/oauth2/access_token","post",new HashMap<String, String>(),new HashMap<String, String>(),map);
        if (post.getStatusLine().getStatusCode()==200){
            String json = EntityUtils.toString(post.getEntity());
            JSONObject jsonObject = JSON.parseObject(json);
            String url= WBUrl.UserInfo.UserInfoUrl
                    .replace("TOKEN",jsonObject.getString("access_token")).replace("UID",jsonObject.getString("uid"));
//            ResponseEntity<String> forEntity = restTemplate.getForEntity(url, String.class);
//            JSONObject jsonObject1 = JSON.parseObject(forEntity.getBody());
            Map<String,String> querys=new HashMap();
            querys.put("access_token",jsonObject.getString("access_token"));
            querys.put("uid",jsonObject.getString("uid"));
            HttpResponse response= HttpUtils.doGet("https://api.weibo.com", "/2/users/show.json", "get", new HashMap<String, String>(), querys);
           if (response.getStatusLine().getStatusCode()==200){
               String json1= EntityUtils.toString(response.getEntity());
               JSONObject jsonObject1 = JSON.parseObject(json1);
               MemberInfoVo infoVo=new MemberInfoVo();
               infoVo.setId(jsonObject1.getString("id"));
               infoVo.setName(jsonObject1.getString("name"));
               infoVo.setGender(jsonObject1.getString("gender"));
               infoVo.setLocation(jsonObject1.getString("location"));
               infoVo.setProfileImageUrl(jsonObject1.getString("profile_image_url"));
               //远程调用
               R r = member.oathuWeiBo(infoVo);

               if (r.getCode()==0){
                   Map data = (Map) r.get("data");
                   String token = JwtUtils.getJwtToken((Integer) data.get("id"),(String) data.get("username") );
                   //response1.setHeader("token",token);
                   return "redirect:http://gulimall.com"+"?token="+token;//+"?token="+token
           }else {
                   return "redirect:http://auth.gulimall.com/login.html";
               }

            }else {
                return "redirect:http://auth.gulimall.com/login.html";
            }
       }else {
           return "redirect:http://auth.gulimall.com/login.html";
        }

   }

   //oauth2.0
  @GetMapping("/oauth2/gitee")
  public  String  oauth2Gitee(@RequestParam String code) throws Exception {
        Map<String,String> header=new HashMap();
        Map<String,String> query=new HashMap();
        Map<String,String> map=new HashMap();
        map.put("grant_type","authorization_code");
        map.put("code",code);
        map.put("client_id","3174d1856bcef201468123db2e049a7b1c89d35fe1764fa3226643e290795764");
        map.put("redirect_uri","http://auth.gulimall.com/oauth2/gitee");
        map.put("client_secret","8f4abb00d0b551bef5af37a2a1e8c52f6420174a1a4b27e8a4d618a3d0fbc825");
        //1 更加code 换取accesstoken
      HttpResponse post = HttpUtils.doPost
              ("https://gitee.com", "/oauth/token", "post", header, query, map);
      if (post.getStatusLine().getStatusCode()==200){
          String json = EntityUtils.toString(post.getEntity());
          Gson gson = new Gson();
          HashMap info = gson.fromJson(json, HashMap.class);
          String  accessToken=(String) info.get("access_token");

          //第一次登录（判断是注册还是登录）
          MemberVo memberVo = member.oathuLogin(accessToken);
          if (memberVo!=null){
              System.out.println(memberVo);
              //登录成功
              return "redirect:http://gulimall.com";

          }else {
              return "redirect:http://auth.gulimall.com/login.html";
          }

      }else {
          return "redirect:http://auth.gulimall.com/login.html";
      }

  }



    public static void main(String[] args) {
        System.out.println(MD5Util.encode("3123456"));
    }
}
